package com.ukao.cashregister.ui.clothinQuery;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gprinterio.GpDevice;
import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.ClothingDetailstImageAdapter;
import com.ukao.cashregister.adapter.OperationStatusAdapter;
import com.ukao.cashregister.base.MvpFragment;
import com.ukao.cashregister.bean.ClothginQuiryBean;
import com.ukao.cashregister.bean.QuiryDetailBean;
import com.ukao.cashregister.bean.ReceiptBean;
import com.ukao.cashregister.bean.StringBean;
import com.ukao.cashregister.consts.Constant;
import com.ukao.cashregister.listener.MyOnItemClickListener;
import com.ukao.cashregister.pesenter.ClothingDetailsPesenter;
import com.ukao.cashregister.printer.PrintMiuiHelper;
import com.ukao.cashregister.printer.PrinterReceipt;
import com.ukao.cashregister.ui.MainActivity;
import com.ukao.cashregister.ui.orderQuiry.OrderQuiryDetailFragment;
import com.ukao.cashregister.utils.CheckUsbDeviceUtils;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.ImageUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.view.ClothingDetailsView;
import com.ukao.cashregister.widget.ShapedImageView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class ClothingDetailsFragment extends MvpFragment<ClothingDetailsPesenter> implements ClothingDetailsView {


    @BindView(R.id.back_layout)
    TextView backLayout;
    @BindView(R.id.isStockOut)
    Button isStockOut;
    @BindView(R.id.isStockRework)
    Button isStockRework;
    @BindView(R.id.right_orders_detail_exception_btn)
    Button rightOrdersDetailExceptionBtn;
    @BindView(R.id.order_detail_tab1)
    RadioButton orderDetailTab1;
    @BindView(R.id.order_detail_tab2)
    RadioButton orderDetailTab2;
    @BindView(R.id.order_detail_tab3)
    RadioButton orderDetailTab3;
    @BindView(R.id.order_detail_tab4)
    RadioButton orderDetailTab4;
    @BindView(R.id.order_detail_tab5)
    RadioButton orderDetailTab5;
    @BindView(R.id.order_detail_group)
    RadioGroup orderDetailGroup;
    @BindView(R.id.clothing_use_information_view)
    View clothingUseInformationView;

    @BindView(R.id.orderNo)
    TextView orderNo;

    @BindView(R.id.storeName)
    TextView storeName;
    @BindView(R.id.factoryName)
    TextView factoryName;
    @BindView(R.id.clothing_details_view)
    View clothingDetailsView;
    @BindView(R.id.total_txt)
    TextView totalTxt;
    @BindView(R.id.txt_scanCode)
    TextView txtscanCode;

    @BindView(R.id.productName)
    TextView productName;
    @BindView(R.id.statusText)
    TextView statusText;
    @BindView(R.id.no)
    TextView no;
    @BindView(R.id.total)
    TextView total;
    @BindView(R.id.serviceName)
    TextView serviceName;
    @BindView(R.id.flawDesc)
    TextView flawDesc;
    @BindView(R.id.addServiceDesc)
    TextView addServiceDesc;
    @BindView(R.id.scanCode)
    TextView scanCode;
    @BindView(R.id.subtotal)
    TextView subtotal;
    @BindView(R.id.tranTypeText)
    TextView tranTypeText;
    @BindView(R.id.tranNum)
    TextView tranNum;
    @BindView(R.id.user_info_icon)
    ShapedImageView userInfoIcon;
    @BindView(R.id.user_info_name)
    TextView userInfoName;
    @BindView(R.id.user_info_wechat_name)
    TextView userInfoWechatName;
    @BindView(R.id.wxId)
    ImageView wxId;
    @BindView(R.id.phone)
    ImageView phone;
    @BindView(R.id.verifyAndriod)
    ImageView verifyAndriod;
    @BindView(R.id.verifyIos)
    ImageView verifyIos;
    @BindView(R.id.verifyPhone)
    ImageView verifyPhone;
    @BindView(R.id.user_info_subscribe)
    TextView userInfoSubscribe;
    @BindView(R.id.user_info_phone_account)
    TextView userInfoPhoneAccount;
    @BindView(R.id.user_info_vip_card_no)
    TextView userInfoVipCardNo;
    @BindView(R.id.user_info_part5_vip_levels_tv)
    TextView userInfoPart5VipLevelsTv;
    @BindView(R.id.user_info_part5_vip_discount)
    TextView userInfoPart5VipDiscount;
    @BindView(R.id.user_info_balance)
    TextView userInfoBalance;
    @BindView(R.id.user_info_credits)
    TextView userInfoCredits;
    @BindView(R.id.user_info_part6_tag1)
    TextView userInfoPart6Tag1;
    @BindView(R.id.user_info_part6_tag2)
    TextView userInfoPart6Tag2;
    @BindView(R.id.user_info_part6_tag3)
    TextView userInfoPart6Tag3;
    @BindView(R.id.logistics_view)
    View logisticsView;
    @BindView(R.id.time_recycler_view)
    RecyclerView timeRecyclerView;
    @BindView(R.id.picture_view)
    View pictureView;
    @BindView(R.id.iamge_recycler_view)
    RecyclerView iamgeRecyclerView;
    @BindView(R.id.scroll_view)
    ScrollView scrollView;
    @BindView(R.id.orderNo_layout)
    LinearLayout orderNoLayout;
    @BindView(R.id.clothing_statusText)
    TextView clothingStatusText;
    @BindView(R.id.right_image)
    ImageView rightImage;
    @BindView(R.id.picCnt)
    TextView picCnt;
    @BindView(R.id.order_detail_accessory)
    ImageView orderDetailAccessory;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.hasRefund)
    TextView hasRefund;
    @BindView(R.id.tv_union_name)
    TextView tvUnionName;  //用户的团体名字


    private ArrayList<String> mPhotoData = new ArrayList<>();
    private List<ClothginQuiryBean.RoductImgBean> mImage = new ArrayList();
    List<QuiryDetailBean.StatusListBean> operations = new ArrayList<>();
    /**
     * 详细图片第几张
     */
    public static final String EXTRA_IMAGE_INDEX = "image_index";
    /**
     * 详细图片集合
     */
    public static final String EXTRA_IMAGE_URLS = "image_data";
    private ClothginQuiryBean mClothginQuiry;
    private Unbinder unbinder;
    private OperationStatusAdapter mOperationAdapter;
    private ClothingDetailstImageAdapter mImageAdapter;
    private int productInfoId;
    private String orderId;

    public static ClothingDetailsFragment newInstance(Serializable mClothginQuiryBean) {
        ClothingDetailsFragment childFragment = new ClothingDetailsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARG_PARAM1, mClothginQuiryBean);
        childFragment.setArguments(bundle);
        return childFragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            Serializable mSerializable = getArguments().getSerializable(ARG_PARAM1);
            mClothginQuiry = (ClothginQuiryBean) mSerializable;
        }
    }

    @Override
    protected ClothingDetailsPesenter createPresenter() {
        return new ClothingDetailsPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_clothing_details, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initListener();
        return view;
    }

    @Override
    protected void initView() {
        rightImage.setVisibility(View.GONE);
        mOperationAdapter = new OperationStatusAdapter(activity, operations);
        timeRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
        timeRecyclerView.setAdapter(mOperationAdapter);

        iamgeRecyclerView.setLayoutManager(new GridLayoutManager(activity, 5));
        mImageAdapter = new ClothingDetailstImageAdapter(activity, mImage);
        iamgeRecyclerView.setAdapter(mImageAdapter);
        fillData();
    }

    private void fillData() {
        ClothginQuiryBean.UserBean mUserBean = mClothginQuiry.getUser();
        ClothginQuiryBean.UserBean.InfoBeanX useInfo = mUserBean.getInfo();
        ClothginQuiryBean.UserBean.UnionInfoBean unionInfoBean = mUserBean.getUnionInfo();

        verifyPhone.setVisibility(useInfo.getVerifyPhone() == 1 ? (View.VISIBLE) : (View.GONE));
        verifyAndriod.setVisibility(useInfo.getVerifyAndriod() == 1 ? (View.VISIBLE) : (View.GONE));
        verifyIos.setVisibility(useInfo.getVerifyIos() == 1 ? (View.VISIBLE) : (View.GONE));
        ImageUtils.loadImage(_mActivity, useInfo.getHeadimgPath(), userInfoIcon);
        if (!TextUtils.isEmpty(useInfo.getName())) {
            userInfoName.setText(useInfo.getName());     //设置用户名
        }
        //设置是不是团体客户
        if (unionInfoBean != null) {
            tvUnionName.setVisibility(View.VISIBLE);
            tvUnionName.setText(unionInfoBean.getName());
        } else {
            tvUnionName.setText("");
            tvUnionName.setVisibility(View.INVISIBLE);
        }
        userInfoPhoneAccount.setText(!CheckUtils.isEmpty(useInfo.getPhone()) == true ? useInfo.getPhone() : "");/*设置手机号手机*/
        userInfoSubscribe.setVisibility(useInfo.getSubscribe() == true ? (View.VISIBLE) : (View.GONE)); /*微信已跑路*/
        wxId.setVisibility(CheckUtils.isEmptyNullNumber(useInfo.getWxId()) == 1 ? (View.VISIBLE) : (View.GONE));
        phone.setVisibility(!CheckUtils.isEmpty(useInfo.getPhone()) == true ? (View.VISIBLE) : (View.GONE));
        verifyPhone.setVisibility(CheckUtils.isEmptyNullNumber(useInfo.getVerifyPhone()) == 1 ? (View.VISIBLE) : (View.GONE));
        verifyAndriod.setVisibility(CheckUtils.isEmptyNullNumber(useInfo.getVerifyAndriod()) == 1 ? (View.VISIBLE) : (View.GONE));
        verifyIos.setVisibility(CheckUtils.isEmptyNullNumber(useInfo.getVerifyIos()) == 1 ? (View.VISIBLE) : (View.GONE));
        userInfoWechatName.setText(CheckUtils.isEmpty(useInfo.getWxNickname()) == true ? "" : "微信昵称：" + useInfo.getWxNickname());
        ImageUtils.loadImage(_mActivity, useInfo.getHeadimgPath(), userInfoIcon);
        userInfoCredits.setText(mUserBean.getExt().getPoint() + "");  /* 积分*/
        //设置余额
        userInfoBalance.setText("￥" + CheckUtils.isEmptyNumber(mUserBean.getExt().getBalance()));

        if (CheckUtils.isEmpty(mClothginQuiry.getStatusList())) {
            timeRecyclerView.setVisibility(View.GONE);
        } else {
            timeRecyclerView.setVisibility(View.VISIBLE);
            mOperationAdapter.setDatas(mClothginQuiry.getStatusList());
        }
        ClothginQuiryBean.UserBean.CardBean mCard = mUserBean.getCard();
        if (!CheckUtils.isNull(mCard)) {
            userInfoVipCardNo.setText(CheckUtils.isEmptyString(mCard.getNo())); /*卡号*/
            userInfoPart5VipLevelsTv.setText(CheckUtils.isEmptyString(mCard.getInfo().getName()));  /*等级*/
            userInfoPart5VipDiscount.setText(mCard.getInfo().getDiscount());       /*折扣*/
        }


        List<ClothginQuiryBean.UserBean.TagListBean> mTagData = mUserBean.getTagList();/*标签*/
        if (!CheckUtils.isEmpty(mTagData)) {
            for (int i = 0; i < mTagData.size(); i++) {

                if (null != mTagData.get(i).getUserTag()) {
                    String name = TextUtils.isEmpty(mTagData.get(i).getUserTag().getName()) ? "" : mTagData.get(i).getUserTag().getName();
                    switch (i) {
                        case 0:
                            userInfoPart6Tag1.setText(name);
                            userInfoPart6Tag1.setVisibility(View.VISIBLE);
                            break;
                        case 1:
                            userInfoPart6Tag2.setText(name);
                            userInfoPart6Tag2.setVisibility(View.VISIBLE);
                            break;
                        case 2:
                            userInfoPart6Tag3.setText(name);
                            userInfoPart6Tag3.setVisibility(View.VISIBLE);
                            break;
                    }
                }
            }


        }


        ClothginQuiryBean.ProductInfoBean mProductInfo = mClothginQuiry.getProductInfo();
    /*退洗标识*/
        if (CheckUtils.isEmpty(mProductInfo.getHasRefundText())) {
            hasRefund.setVisibility(View.GONE);

        } else {
            hasRefund.setText(mProductInfo.getHasRefundText());
            hasRefund.setVisibility(View.VISIBLE);
        }
        productInfoId = mProductInfo.getId();
        orderId = mProductInfo.getOrderId();
        rightOrdersDetailExceptionBtn.setVisibility(mProductInfo.isEnablePrint() ? View.VISIBLE : View.GONE);
        no.setText(mProductInfo.getNo());
        scanCode.setText(mProductInfo.getScanCode());
        orderNo.setText(CheckUtils.isEmptyString(mProductInfo.getOrderNo()));
        statusText.setText(CheckUtils.isEmptyString(mProductInfo.getStatusText()));
        clothingStatusText.setText(CheckUtils.isEmptyString(mProductInfo.getStatusText()));
        storeName.setText(CheckUtils.isEmptyString(mProductInfo.getStoreName()));
        factoryName.setText(CheckUtils.isEmptyString(mProductInfo.getFactoryName()));
        totalTxt.setText("该订单共" + CheckUtils.isEmptyString(mProductInfo.getTotal() + "件衣物。"));

        if (mProductInfo.getType() == 1) {/*衣物*/
            orderDetailAccessory.setVisibility(View.GONE);
            productName.setText(mProductInfo.getProductName());

        } else {/*附件*/
            orderDetailAccessory.setVisibility(View.VISIBLE);
            productName.setText("附件：" + mProductInfo.getProductName());

        }

        total.setText(mProductInfo.getTotal() + "");
        Gson mGson = new Gson();

        StringBuffer mColorBuffer = new StringBuffer();
        if (!CheckUtils.isEmpty(mProductInfo.getColorDesc())) {
            List<StringBean> mColorDesclist = mGson.fromJson(mProductInfo.getColorDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());


            for (int i = 0; i < mColorDesclist.size(); i++) {
                if (i != mColorDesclist.size() - 1) {
                    mColorBuffer.append(mColorDesclist.get(i).getName() + "/");
                } else {
                    mColorBuffer.append(mColorDesclist.get(i).getName());
                }
            }


        }

        String annexDesc = "";
        if (!CheckUtils.isEmpty(mProductInfo.getAnnexDesc())) {/*附件*/
            List<StringBean> mAnnexDesclist = mGson.fromJson(mProductInfo.getAnnexDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());

            StringBuffer mStringBuffer3 = new StringBuffer();
            for (int i = 0; i < mAnnexDesclist.size(); i++) {
                if (i != mAnnexDesclist.size() - 1) {
                    mStringBuffer3.append(mAnnexDesclist.get(i).getName() + "/");
                } else {
                    mStringBuffer3.append(mAnnexDesclist.get(i).getName());
                }


            }
            annexDesc = mStringBuffer3.toString();

        }
        if (!CheckUtils.isEmpty(annexDesc)) {
            annexDesc = "附件：" + annexDesc;
        }
        if (!CheckUtils.isNull(mProductInfo.getPicCnt())) {
            if (mProductInfo.getPicCnt() != 0) {
                picCnt.setText("衣物照片：" + mProductInfo.getPicCnt());
            } else {
                picCnt.setText("衣物照片：" + "无");
            }

        } else {
            picCnt.setText("衣物照片：" + "无");
        }


        serviceName.setText(mProductInfo.getServiceName() + mColorBuffer.toString() + "￥" + CheckUtils.isEmptyNumber(mProductInfo.getSaleAmt()) + annexDesc);
        if (!CheckUtils.isEmpty(mProductInfo.getFlawDesc())) {
            List<StringBean> mflawDesclist = mGson.fromJson(mProductInfo.getFlawDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            StringBuffer mStringBuffer = new StringBuffer();
            for (int i = 0; i < mflawDesclist.size(); i++) {
                if (i != mflawDesclist.size() - 1) {
                    mStringBuffer.append(mflawDesclist.get(i).getName() + "/");
                } else {
                    mStringBuffer.append(mflawDesclist.get(i).getName());
                }
            }
            flawDesc.setText(mStringBuffer.toString());


        }

        if (!CheckUtils.isEmpty(mProductInfo.getAddServiceDesc())) {
            List<StringBean> mServiceDesclist = mGson.fromJson(mProductInfo.getAddServiceDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            StringBuffer mStringBuffer = new StringBuffer();
            for (int i = 0; i < mServiceDesclist.size(); i++) {
                StringBean mitem = mServiceDesclist.get(i);
                mStringBuffer.append(mitem.getName()).append("￥").append(CheckUtils.isEmptyNumber(mitem.getAmt()));

            }
            addServiceDesc.setText(mStringBuffer.toString());


        }

        txtscanCode.setText(CheckUtils.isEmptyString(mProductInfo.getScanCode()));
        scanCode.setText("条码:" + CheckUtils.isEmptyString(mProductInfo.getScanCode()));
        subtotal.setText("小计:￥" + CheckUtils.isEmptyNumber(mProductInfo.getSubtotal()));
        tranTypeText.setText(CheckUtils.isEmptyString(mProductInfo.getTranTypeText()));
        tranNum.setText(CheckUtils.isEmptyString(mProductInfo.getTranNum()));
        if (CheckUtils.isEmpty(mClothginQuiry.getProductImgList()))
            iamgeRecyclerView.setVisibility(View.GONE);
        else {
            iamgeRecyclerView.setVisibility(View.VISIBLE);
            mImageAdapter.setDatas(mClothginQuiry.getProductImgList());
            for (ClothginQuiryBean.RoductImgBean roductImgBean : mClothginQuiry.getProductImgList()) {
                mPhotoData.add(roductImgBean.getCameraImg());
            }


        }
        if (mProductInfo.getIsStockOut() != 1) {/*是否能出库*/
            isStockOut.setVisibility(View.GONE);
        }
        if (mProductInfo.getIsStockOut() != 1) {//能质检返工
            isStockRework.setVisibility(View.GONE);
        }


    }

    @Override
    protected void initListener() {
        super.initListener();
        mImageAdapter.setOnItemClickListener(mOnItemClickListener);

    }

    private OnItemClickListener mOnItemClickListener = new MyOnItemClickListener() {

        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            Intent mIntent = new Intent(_mActivity, PhotoActivity.class);
            mIntent.putStringArrayListExtra(ARG_PARAM1, mPhotoData);
            mIntent.putExtra(ARG_PARAM2, i);
            startActivity(mIntent);


        }
    };


    @OnCheckedChanged({R.id.order_detail_tab1, R.id.order_detail_tab2, R.id.order_detail_tab3, R.id.order_detail_tab4, R.id.order_detail_tab5})
    public void OnCheckedChanged(CompoundButton view, boolean check) {
        if (check)
            switch (view.getId()) {
                case R.id.order_detail_tab1:
                    Constant.scrollToView(scrollView, clothingUseInformationView);
                    break;
                case R.id.order_detail_tab2:
                    Constant.scrollToView(scrollView, clothingDetailsView);
                    break;
                case R.id.order_detail_tab3:
                    Constant.scrollToView(scrollView, clothingUseInformationView);
                    break;
                case R.id.order_detail_tab4:
                    Constant.scrollToView(scrollView, logisticsView);
                    break;
                case R.id.order_detail_tab5:
                    Constant.scrollToView(scrollView, pictureView);
                    break;

            }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.isStockOut, R.id.isStockRework, R.id.back_layout, R.id.orderNo_layout, R.id.right_orders_detail_exception_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.right_orders_detail_exception_btn:

                if (CheckUtils.isMIUIDevices()) {
                    mvpPresenter.printReceipt(_mActivity, orderId);
                } else if (CheckUsbDeviceUtils.isReceipt()) {/*小票*/
                    mvpPresenter.printReceipt(_mActivity, orderId);

                }

                break;

            case R.id.isStockOut:

                mvpPresenter.stockOut(_mActivity, productInfoId + "");
                break;
            case R.id.isStockRework:
                mvpPresenter.stockRework(_mActivity, productInfoId + "");
                break;
            case R.id.back_layout:
                finish();
                break;
            case R.id.orderNo_layout:
                if (!CheckUtils.isEmpty(orderId))
                    start(OrderQuiryDetailFragment.newInstance(orderId + "", "衣物详情"), SINGLETASK);
                break;

        }
    }

    @Override
    public void loadSuccess(String message) {
        T.show(message);
    }

    @Override
    public void loadFail(String message) {
        T.show(message);
    }

    @Override
    public void loadReceipt(ReceiptBean mReceiptBean) {
        if (CheckUtils.isMIUIDevices()) {
            PrintMiuiHelper.receiptReceipt(MainActivity.getPrintService(), mReceiptBean);
        } else {
            PrinterReceipt mPrinterReceipt = new PrinterReceipt();
            GpDevice mDevice = new GpDevice();
            mPrinterReceipt.printGp80(mReceiptBean, mDevice);

        }


    }
}
